package com.screen.screendisplay.service.impl.ne;

import com.screen.screendisplay.entity.ne.NeSafetyenvRiskTask;
import com.screen.screendisplay.mapper.ne.NeSafetyenvRiskTaskMapper;
import com.screen.screendisplay.service.ne.NeSafetyenvRiskTaskService;
import com.screen.screendisplay.vo.ne.NeHighRiskWorkVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 高风险作业统计表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeSafetyenvRiskTaskServiceImpl extends ServiceImpl<NeSafetyenvRiskTaskMapper, NeSafetyenvRiskTask> implements NeSafetyenvRiskTaskService {

    @Override
    public List<NeHighRiskWorkVO> getHighRiskWork(Integer year) {
        System.out.println("=== getHighRiskWork called with year: " + year + " ===");
        
        // 获取当前日期
        LocalDate now = LocalDate.now();
        
        // 确定查询的年月范围（最近6个月）
        List<String> monthList = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            LocalDate monthDate = now.minusMonths(i);
            monthList.add(String.format("%04d-%02d", monthDate.getYear(), monthDate.getMonthValue()));
        }
        
        System.out.println("Month list for query: " + monthList);
        
        // 构建查询条件
        QueryWrapper<NeSafetyenvRiskTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("date", monthList);
        
        // 如果指定了年份，则只查询该年份的数据
        if (year != null) {
            queryWrapper.eq("year", year);
        }
        
        queryWrapper.orderByDesc("year", "month");
        
        List<NeSafetyenvRiskTask> entities = this.list(queryWrapper);
        System.out.println("Found " + entities.size() + " entities from database");
        
        // 按年月汇总数据
        Map<String, List<NeSafetyenvRiskTask>> monthMap = entities.stream()
                .collect(Collectors.groupingBy(entity -> 
                    String.format("%04d-%02d", entity.getYear(), entity.getMonth())));
        
        List<NeHighRiskWorkVO> resultList = new ArrayList<>();
        
        // 生成最近6个月的数据（如果没有指定年份）
        if (year == null) {
            for (int i = 0; i < 6; i++) {
                LocalDate monthDate = now.minusMonths(i);
                String monthKey = String.format("%04d-%02d", monthDate.getYear(), monthDate.getMonthValue());
                NeHighRiskWorkVO vo = createMonthlyData(monthDate.getYear(), monthDate.getMonthValue(), monthMap.get(monthKey));
                resultList.add(vo);
            }
        } else {
            // 返回指定年份的所有月份数据
            for (int month = 12; month >= 1; month--) {
                String monthKey = String.format("%04d-%02d", year, month);
                if (monthMap.containsKey(monthKey)) {
                    NeHighRiskWorkVO vo = createMonthlyData(year, month, monthMap.get(monthKey));
                    resultList.add(vo);
                }
            }
        }
        
        return resultList;
    }
    
    /**
     * 创建月度汇总数据
     */
    private NeHighRiskWorkVO createMonthlyData(Integer year, Integer month, List<NeSafetyenvRiskTask> monthData) {
        NeHighRiskWorkVO vo = new NeHighRiskWorkVO();
        vo.setYear(year);
        vo.setMonth(month);
        
        if (monthData != null && !monthData.isEmpty()) {
            // 汇总该月份所有区域和场站的数据
            int totalTasks = monthData.stream()
                    .mapToInt(entity -> entity.getHighRiskTasks() != null ? entity.getHighRiskTasks() : 0)
                    .sum();
            
            int totalWorkers = monthData.stream()
                    .mapToInt(entity -> entity.getHighRiskWorkers() != null ? entity.getHighRiskWorkers() : 0)
                    .sum();
            
            vo.setHighRiskTasks(totalTasks);
            vo.setHighRiskWorkers(totalWorkers);
        } else {
            // 如果没有数据，设置为0
            vo.setHighRiskTasks(0);
            vo.setHighRiskWorkers(0);
        }
        
        return vo;
    }

}
